// 导入表单属性、行为类型以及表单钩子返回类型的类型定义
import type { FormProps, FormActionType, UseFormReturnType } from '../types/form';

// 导入动态属性的类型定义
import type { DynamicProps } from '/#/utils';

// 导入Vue的响应式API：ref, onUnmounted, unref, nextTick, watch
import { ref, onUnmounted, unref, nextTick, watch } from 'vue';

// 导入判断是否是生产环境的函数
import { isProdMode } from '@/utils/env';

// 导入获取动态属性的函数
import { getDynamicProps } from '@/utils';

// 声明Props类型，它是FormProps的动态属性的Partial类型
type Props = Partial<DynamicProps<FormProps>>;

// 定义useForm函数，它接受可选的props参数
export function useForm(props?: Props): UseFormReturnType {
  // 创建一个响应式引用，用于存储表单实例
  const formRef = ref<Nullable<FormActionType>>(null);
  // 创建一个响应式引用，用于标记表单是否已加载
  const loadedRef = ref<Nullable<boolean>>(false);

  // getForm函数，用于获取表单实例
  async function getForm() {
    const form = unref(formRef);
    if (!form) {
      console.error('表单实例尚未获取，请确保在执行表单操作时表单已经被渲染！');
    }
    await nextTick();
    return form as FormActionType;
  }

  // register函数，用于注册表单实例
  function register(instance: FormActionType) {
    isProdMode() &&
      onUnmounted(() => {
        formRef.value = null;
        loadedRef.value = null;
      });
    if (unref(loadedRef) && isProdMode() && instance === unref(formRef)) return;

    formRef.value = instance;
    loadedRef.value = true;

    // 监听props的变化，并更新表单属性
    watch(
      () => props,
      () => {
        props && instance.setProps(getDynamicProps(props));
      },
      {
        immediate: true,
        deep: true,
      },
    );
  }

  // 定义表单行为的方法对象
  const methods: FormActionType = {
    // 设置表单属性
    setProps: async (formProps: Partial<FormProps>) => {
      const form = await getForm();
      await form.setProps(formProps);
    },
    // 重置表单字段
    resetFields: async () => {
      getForm().then(async (form) => {
        await form.resetFields();
      });
    },
    // 清除表单验证
    clearValidate: async (name?: string | string[]) => {
      const form = await getForm();
      await form.clearValidate(name);
    },
    // 获取表单字段值
    getFieldsValue: <T>() => {
      return unref(formRef)?.getFieldsValue() as T;
    },
    // 设置表单字段值
    setFieldsValue: async <T>(values: T) => {
      const form = await getForm();
      await form.setFieldsValue(values as Recordable<any>);
    },
    // 提交表单
    submit: async (): Promise<any> => {
      const form = await getForm();
      return form.submit();
    },
    // 验证表单字段
    validate: async (nameList?: any[]): Promise<Recordable> => {
      const form = await getForm();
      return form.validate(nameList);
    },
    // 设置加载子状态
    setLoadingSub: (value: boolean) => {
      loadedRef.value = value;
    },
    // 设置表单项
    setSchema: async (values) => {
      const form = await getForm();
      form.setSchema(values);
    },
  };

  // 返回注册函数和表单行为的方法对象
  return [register, methods];
}
